package com.bjian.CodeSandBox.unitl;

import com.bjian.CodeSandBox.unitl.model.ExeuteMessage;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ProcessUtil {

    public static ExeuteMessage runProcessAndGetMessage(Process runProcess, String opName) {
        ExeuteMessage exeuteMessage = new ExeuteMessage();
        StringBuilder compileOutputStringBuilder = new StringBuilder();
        InputStream runProcessInputStream = runProcess.getInputStream();
        InputStream processErrorStream = runProcess.getErrorStream();
        try {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            int exitValue = runProcess.waitFor();
            exeuteMessage.setExitValue(exitValue);
            if (exitValue == 0) {//正常退出
                //读取正常执行返回的信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcessInputStream));
                String tempResult;
                while ((tempResult = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(tempResult);
                }
                exeuteMessage.setMessage(compileOutputStringBuilder.toString());
            } else {//异常推出
                //读取错误执行返回的正常信息
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(runProcessInputStream));
                String tempResult;
                while ((tempResult = bufferedReader.readLine()) != null) {
                    compileOutputStringBuilder.append(tempResult);
                }
                exeuteMessage.setMessage(compileOutputStringBuilder.toString());
                //读取错误执行返回的错误信息
                BufferedReader ErrorBufferedReader = new BufferedReader(new InputStreamReader(processErrorStream));
                StringBuilder ErrorcompileOutputStringBuilder = new StringBuilder();
                String ErrorTempResult;
                while (((ErrorTempResult = ErrorBufferedReader.readLine()) != null)) {
                    ErrorcompileOutputStringBuilder.append(ErrorTempResult);
                }
                exeuteMessage.setErrorMessage(ErrorcompileOutputStringBuilder.toString());
            }
            stopWatch.stop();
            exeuteMessage.setRunTime(stopWatch.getLastTaskTimeMillis());

        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                runProcessInputStream.close();
                processErrorStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return exeuteMessage;
    }

}
